package top.huhuiyu.javabasic.javabasictemplate;

import top.huhuiyu.javabasic.javabasictemplate.dao.TbNewsDAO;
import top.huhuiyu.javabasic.javabasictemplate.entity.CommonInfo;
import top.huhuiyu.javabasic.javabasictemplate.entity.TbNews;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(urlPatterns = "/news/add.action")
public class AddNewsServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        TbNews news = new TbNews();
        news.setTitle(req.getParameter("title"));
        news.setInfo(req.getParameter("info"));
        news.setSource(req.getParameter("source"));
        try {
            TbNewsDAO.add(news);
        } catch (SQLException e) {
            throw new ServletException(e);
        }
        CommonInfo info = new CommonInfo("添加信息成功", String.format("%s%s", req.getContextPath(), "/news/list.action"));
        req.setAttribute("info", info);
        req.getRequestDispatcher("/common.jsp").forward(req, resp);
    }
}
